<template>
	<div class="like-section">
		<div class="like-grid">
			<div class="like-card" v-for="(item, index) in likeHouses" :key="index">
				<img :src="item.imageUrls[0]" alt="房源图片" class="like-image" @click="goToDetails(item.id)" />
				<div class="like-info">
					<text class="like-title" @click="goToDetails(item.id)">{{ item.title }}</text>
					<p class="like-details">
						<span @click="goToList({ businessArea: item.businessArea })"> [{{ item.businessArea }}] </span>
						<span @click="goToList({ subwayStation: item.subwayStation })"> 近{{ item.subwayStation }}地铁站 </span>
					</p>
				</div>
				<p class="like-price">￥{{ item.price }}</p>
			</div>
		</div>
	</div>
</template>

<script>
	import userApi from '@/api/userApi';
	import router from '@/router'; // 根据项目实际路径调整

	export default {
		name: 'GuessYouLike',
		data() {
			return {
				likeHouses: [] // 存储猜你喜欢的房源数据
			};
		},
		created() {
			this.fetchLikeHouses();
		},
		methods: {
			fetchLikeHouses() {
				// if (localStorage.getItem('role')!== 'user')
				//如果没有登录
				if (!localStorage.getItem('satoken')) {
					userApi.getHouses(1, 6).then((res) => {
						this.likeHouses = (res.data.houses || []).slice(0, 6);
					});
				} else {
					userApi
						.getGuessYouLike(1, 10)
						.then((res) => {
							if (res.code === 401){
								userApi.getHouses(1, 6).then((res) => {
									this.likeHouses = (res.data.houses || []).slice(0, 6);
								});
							}

							this.likeHouses = (res.data.houses || []).slice(0, 6);
						})
				}
			},
			goToDetails(houseId) {
				// 跳转到房源详情页
				window.open(`/house-details/${houseId}`, '_blank');
			},
			goToList(filter) {
				// 根据筛选条件跳转到房源列表页
				console.log('筛选条件:', filter);
				router.push({ name: 'HouseList', query: filter }).then(() => {
					window.location.reload();
				});
			}
		}
	};
</script>

<style scoped>
	.like-section {
		max-width: 1200px;
		margin-bottom: 2rem;
	}

	.like-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr); /* 一行显示3个 */
		gap: 1rem;
	}

	.like-card {
		border: 1px solid #ddd;
		background-color: #fff;
		position: relative;
		/* 可以设置固定高度或自适应 */
	}

	.like-image {
		width: 100%;
		height: 200px;
		object-fit: cover;
		cursor: pointer;
	}

	.like-info {
		padding: 0.5rem;
	}

	.like-title {
		font-size: 16px;
		font-weight: bold;
		margin: 0;
		cursor: pointer;
	}

	.like-details {
		font-size: 14px;
		color: #777;
		margin-top: 0.5rem;
	}

	.like-details span {
		margin-right: 0.5rem;
		cursor: pointer;
	}

	.like-details span:hover {
		color: #ff6a00;
	}

	.like-price {
		position: absolute;
		right: 0.5rem;
		bottom: 1.2rem;
		font-size: 16px;
		font-weight: bold;
		color: #f60;
		margin: 0;
	}
</style>
